(* ::Package:: *)

(************************************************************************)
(* This file was generated automatically by the Mathematica front end.  *)
(* It contains Initialization cells from a Notebook file, which         *)
(* typically will have the same name as this file except ending in      *)
(* ".nb" instead of ".m".                                               *)
(*                                                                      *)
(* This file is intended to be loaded into the Mathematica kernel using *)
(* the package loading commands Get or Needs.  Doing so is equivalent   *)
(* to using the Evaluate Initialization Cells menu command in the front *)
(* end.                                                                 *)
(*                                                                      *)
(* DO NOT EDIT THIS FILE.  This entire file is regenerated              *)
(* automatically each time the parent Notebook file is saved in the     *)
(* Mathematica front end.  Any changes you make to this file will be    *)
(* overwritten.                                                         *)
(************************************************************************)



basedir= If[$FrontEnd===Null,Directory[], NotebookDirectory[]]
scriptinfo = If[$FrontEnd===Null,
"Running package kernell only",
 ToFileName[("FileName" /. NotebookInformation[])[[1]],("FileName" /. NotebookInformation[])[[2]]]]


LogTest`Setup[]:=
If[LogTest`testLoggingEnabled,
Print["Logging Enabled"];
LogTest`testNumber = 1;
LogTest`fn =ToFileName[ basedir,"logTest.txt"];
LogTest`os = OpenWrite[LogTest`fn];
WriteString[LogTest`os,"Starting Test logging","\n"];
WriteString[LogTest`os,scriptinfo,"\n"];
WriteString[LogTest`os,DateString[],"\n\n"];
Close[LogTest`os];
]

LogTest`Test[LogTest`testName_String,LogTest`test_ /; LogTest`test \[Element] Booleans]:=
 (
LogTest`result ="did not run";
If[LogTest`test,LogTest`result = "pass";,LogTest`result = "fail";];
LogTest`str = StringForm["`1`...`2`",LogTest`testName,LogTest`result];
Print["Running the test named: ",LogTest`str];
If[LogTest`testLoggingEnabled,
LogTest`os =OpenAppend[LogTest`fn];
WriteString[LogTest`os,"Test ",LogTest`testNumber++,") ",LogTest`str,"\n"];
Close[LogTest`os];,
Null
]
)

LogTest`TestName[LogTest`testName_String]:=
 (
LogTest`start = AbsoluteTime[];
LogTest`result ="did not run";
LogTest`strTestName = StringForm["`1`",LogTest`testName];
Print["Running the test named: ",LogTest`strTestName];
If[LogTest`testLoggingEnabled,
LogTest`os =OpenAppend[LogTest`fn];
WriteString[LogTest`os,"Test ",LogTest`testNumber++,") ",LogTest`strTestName];
Close[LogTest`os];,
Null
]
)
LogTest`Assert[LogTest`test_ /; LogTest`test \[Element] Booleans]:=
 (
LogTest`finish = AbsoluteTime[];
LogTest`testtime = LogTest`finish - LogTest`start;
If[LogTest`test,LogTest`result = "pass";,LogTest`result = "fail";];
LogTest`strResult = StringForm[" -- (`1` seconds)...`2`", Round[LogTest`testtime,.01], LogTest`result];
Print["The test named: ",LogTest`strTestName, LogTest`strResult];
If[LogTest`testLoggingEnabled,
LogTest`os =OpenAppend[LogTest`fn];
WriteString[LogTest`os,LogTest`strResult,"\n"];
Close[LogTest`os];,
Null
]
)

LogTest`Message[LogTest`messageText_String]:=
(
If[LogTest`testLoggingEnabled,
LogTest`os =OpenAppend[LogTest`fn];
WriteString[LogTest`os,LogTest`messageText,"\n"];
Close[LogTest`os];,
Null
]
)

LogTest`TallyTests[]:=
(
If[LogTest`testLoggingEnabled,
(
LogTest`ss=StringJoin[ReadList[LogTest`fn,String]];
LogTest`totals = {StringCount[LogTest`ss,"..."],StringCount[LogTest`ss,"...pass"],StringCount[LogTest`ss,"...fail"]};
If[LogTest`totals[[3]] ==0, LogTest`str="Success!\n", LogTest`str = "Failure!!\n"];
LogTest`str = LogTest`str <> ToString[StringForm["`1` total tests `2` tests passed `3` tests failed",#1 ,#2,#3]& @@LogTest`totals]
),
Print["Test Logging not enabled"];
]
)

LogTest`testLoggingEnabled =True;
LogTest`Setup[]
Names["Global`*"]
Names["LogTest`*"]


DAQTesting = True;  (* set to anyvalue for now *)
exeDirDefault =ToFileName[{ParentDirectory[ParentDirectory[basedir]],"build_MinGW","Debug"}];
(* exeDir may be set from command line when testing *) 
exeDir =  If[ValueQ[exeDir],
(Print["Using choosen executable directory: ",exeDir]; exeDir),
 (Print["Using default executabe directory: ", exeDirDefault];exeDirDefault)
];
SetDirectory[exeDir]
LogTest`Message["The executable file called is in the following directory"]
LogTest`Message[ToString[exeDir]]
LogTest`Message["***"]

LogTest`TestName["Checking that the link is established"];
t1=AbsoluteTime[];
Needs["DAQ`DataAcquisition`",ToFileName[ParentDirectory[basedir],"DataAcquisition.m"]]
(* or  <<"C:\\math\\mathDAQ\\Package\\DataAcquisition.m" *)
Print["Time needed to establish the link by itself: ", AbsoluteTime[] - t1];
ResetDirectory[];
Needs["ErrorBarPlots`"]
(* Links["getvolt*"] *)
Clear[DAQTesting];
theLink=Links["mathDAQ*"]
LogTest`Assert[Length[theLink] ==1];


LogTest`TestName["Outputting a single voltage on Channel 0"]
volt =1.0;answer =0;
OutputWaveform[{0},{volt},1,1];
answer =Mean[GetVoltages[{0},1000,100,IncludeTime->Omit]];
OutputWaveform[{0},{0},1,1];
Print[ "Output channel 0 error in volt is: ",volt-answer, " Volts"];
(* LogTest`Test["Outputting a single voltage on channel 0",Abs[volt-answer] <=.02]; *)
LogTest`Assert[Abs[volt-answer] <=.02];

LogTest`TestName["Outputting a single voltage on Channel 1"]
volt =2.0;answer =0;
OutputWaveform[{1},{volt},1,1];
answer =Mean[GetVoltages[{3},1000,100,IncludeTime->Omit]];
OutputWaveform[{1},{0},1,1, MessageLevel -> 0];
Print[ "Output channel 1 error in volt is: ",volt-answer, " Volts"];
LogTest`Assert[Abs[volt-answer] <=.02];


LogTest`TestName["Outputting a voltages on channels 0 and 1"];
volt0 =2.4;volt1=-1.78;Clear[answer];
OutputWaveform[{0, 1}, {{volt0},{volt1}}, 1, 1, MessageLevel -> 0]
answer=Mean[Transpose[GetVoltages[{0,3},60,10,IncludeTime->Omit]]];
Print[ "Output errors:\nChannel 0 = ",volt0-answer[[0+1]], " Volts\n","Channel 1 = ",volt1 -answer[[1+1]], " Volts"];
OutputWaveform[{0,1},{{0},{0}},1,1, MessageLevel -> 0];
LogTest`Assert[(Abs[volt0-answer[[0+1]]]) <= 0.02 && (Abs[volt1 -answer[[1+1]]] <= 0.02)];


LogTest`TestName["Outputting repeatedly using slow IMMEDIATE transfer on channels 0 and 1"]
Clear[answer];
inputData = Table[5.0*{{Sin[x]},{Cos[x]}}//N,{x,0,2*Pi-2*Pi/100,2*Pi/50}];
answer =Table [{OutputWaveform[{0,1},p,10,10],GetVoltages[{0,3},100,1,IncludeTime->Omit]}[[2]], {p,inputData}];
ListPlot[{Take[Flatten[inputData,2],{1,-1,2}],Take[Flatten[answer,2],{1,-1,2}]}]
LogTest`pointsInError = Count[Abs[Flatten[inputData,2]- Flatten[answer,2]],x_ /; x>= .02]
OutputWaveform[{0,1},{{0},{0}},1,1, MessageLevel -> 0];
LogTest`Assert[LogTest`pointsInError ==0]


LogTest`TestName["Using setup only option to ouput single voltage on channel 0"];
volt =1.80;answer =0;
thWrite = OutputWaveform[{0},{0.0},10,10,SetupOnly ->True];
RunTask[thWrite,volt];
answer=Mean[GetVoltages[{0},60,10,IncludeTime->Omit]];
Print[ "Output channel 0 error in volt is: ",volt-answer, " Volts"];
(* LogTest`Test["Using setup only option to ouput single voltage on channel 0",Abs[volt-answer] <=.02]; *)
RunTask[thWrite,0.0];
ClearTask[thWrite];
LogTest`Assert[Abs[volt-answer] <=.02];


LogTest`TestName["Using setup only option to ouput on two channels"];
volt0 =-1.8;volt1=-0.78;Clear[answer];
OutputWaveform[{0, 1}, {{volt0},{volt1}}, 1, 1, SetupOnly->True,MessageLevel -> 0];
RunTask[thWrite,{volt0,volt1}];
answer=Mean[Transpose[GetVoltages[{0,3},60,10,IncludeTime->Omit]]];
Print[ "Output errors:\nChannel 0 = ",volt0-answer[[0+1]], " Volts\n","Channel 1 = ",volt1 -answer[[1+1]], " Volts"];
RunTask[thWrite,{0,0}];
ClearTask[thWrite];
LogTest`Assert[(Abs[volt0-answer[[0+1]]]) <= 0.02 && (Abs[volt1 -answer[[1+1]]] <= 0.02)];


thWrite = OutputWaveform[{0},{.4},10,10,SetupOnly ->True];
Table[RunTask[thWrite,Sin[x]//N],{x,0,4*Pi,2*Pi/100}];
ClearTask[thWrite];


thWrite = OutputWaveform[{0,1},{{1.0},{2.0}},10,10,SetupOnly ->True,MessageLevel->0];
Table[RunTask[thWrite,{Sin[x],Cos[x]}//N],{x,0,4*Pi,2*Pi/100}];
RunTask[thWrite,{0,0}];
ClearTask[thWrite];


LogTest`TestName["Outputting and Reading repeatedly on channels 0 and 1 using SetupOnly and RunTask for both"]
inputData = Table[{{Sin[x]},{Cos[x]}}//N,{x,0,8*Pi,2*Pi/100}];
thWrite = OutputWaveform[{0,1},{{0.0},{0.0}},10,10,SetupOnly->True];
thRead = GetVoltages[{0,3},60,1,SetupOnly->True, MessageLevel->0];
answer =Table [{RunTask[thWrite,Flatten[p]],RunTask[thRead]}[[2]], {p,inputData}];
ListPlot[Flatten[answer,2]]
ListPlot[Flatten[inputData,2]-Flatten[answer,2]];
LogTest`pointsInError = Count[Abs[Flatten[inputData,2]- Flatten[answer,2]],x_ /; x>= .02]

RunTask[thWrite,{0,0}];
ClearTask[thWrite];
ClearTask[thRead];
LogTest`Assert[LogTest`pointsInError ==0]



LogTest`TestName["Setup Only works independently for output channels"];
thWrite0 = OutputWaveform[{0},{0.0},10,10,SetupOnly->True,MessageLevel->0];
thWrite1 = OutputWaveform[{1},{0.0},10,10,SetupOnly->True,MessageLevel->0];
(* thWrite1 = OutputWaveform[{3},{0.0},10,10,SetupOnly->True,MessageLevel->0] CRASHES mathDAQ *)
val0 =0.50; val1= -0.7;
RunTask[thWrite0,val0];
RunTask[thWrite1,val1];
answer =Mean[Transpose[GetVoltages[{0,3},1000,100,IncludeTime->Omit]]]
RunTask[thWrite0,0];
RunTask[thWrite1,0];
ClearTask[thWrite0];
ClearTask[thWrite1];
LogTest`Assert[(Abs[val0-answer[[0+1]]]) <= 0.02 && (Abs[val1 -answer[[1+1]]] <= 0.02)];


LogTest`TestName["Setup Only is faster than immediate mode for repeated read"];
OutputWaveform[{0, 1},{{1.23},{2.34}},1000.0,1,MessageLevel->0];
thRead = GetVoltages[{0,3},60,1,SetupOnly->True, MessageLevel->0];
iterations1=800; iterations2 = 20;
ts = AbsoluteTime[];
	Table[RunTask[thRead],{i,0,iterations1}];
tSetup = AbsoluteTime[] -ts
RunTask[thRead];
ClearTask[thRead];
ts = AbsoluteTime[];
	Table[GetVoltages[{0,3},60,1, IncludeTime->Omit],{i,0,iterations2}];
tImmediate  = AbsoluteTime[] -ts
GetVoltages[{0,3},60,1, IncludeTime->Omit]
OutputWaveform[{0, 1},{{0.5},{0.5}},1000.0,1]
(*  TODO:  Understand why follow cause a problem
	OutputWaveform[{0, 1},{0.5,0.5},1000.0,1]
	This syntax is accepted and change voltage but will cause python test runner to hang
 *)
setupOnlyIPS= iterations1/tSetup//N;
ImmediateModeIPS = iterations2/tImmediate//N;
Print["Using setupOnly: ",setupOnlyIPS ," reads/second"];
Print["Using Immediate mode: ", ImmediateModeIPS, " reads/second"];
LogTest`Assert[setupOnlyIPS > ImmediateModeIPS];



(* Pause[.1] *)
LogTest`TestName["Outputing waveform single channel using interrupts"];
numPts =200;
offset = 0.9;
data = Table[Sin[x+offset]//N,{x,0,2* Pi-2*Pi/numPts,2*Pi/numPts}];
freqWritePts=1500.0;
freqWave = freqWritePts/numPts;
freqReadPts =2000.0;
ii=0;
dataForPlot=Table[{ii++/freqWritePts,p}, {p,data}];
th = OutputWaveform[{0},data, freqWritePts,1,SampleMode -> Continuous,TransferMechanism -> Interrupts,MessageLevel ->0];
answer = GetVoltages[{0},freqReadPts,250,MessageLevel->0,TransferMechanism -> DMA];
ListPlot[answer,Joined->False]
ClearTask[th];
ff[x_,B_,p2_]:= If[answer[[1,2]] < answer[[p2,2]], Sin[2*Pi*freqWave*x +B],
-Sin[2*Pi*freqWave*x -B]]
pt2 = If[freqReadPts < freqWritePts,1,Round[freqReadPts/freqWritePts+2]]
B = ArcSin[answer[[1,2]]];
Plot[ff[x,B,pt2],{x,answer[[1,1]],answer[[-1,1]]}];
ListPlot[answer];
Show[%,%%]
aveErr  =Total[Table[Abs[ff[x[[1]],B,pt2] - x[[2]]],{x,answer}]]/Length[answer]
LogTest`Assert[aveErr < .05];


(* constants hardcoded at the moment *)
LogTest`TestName["Outputing waveform single channel using DMA"];
data = Table[3*Sin[x]//N,{x,0,2* Pi-2*Pi/100,2*Pi/100}];
freqOut=1000.0; freqIn =1000.0
ii=0;
dataForPlot=Table[{ii++/freqOut,p}, {p,data}];
th = OutputWaveform[{0},data, freqOut,3,SampleMode ->Continuous,TransferMechanism -> DMA,MessageLevel ->0]
answer = GetVoltages[{0},freqIn,200,MessageLevel->0,TransferMechanism ->Interrupts];
ListPlot[{dataForPlot,answer},Joined->False];
ClearTask[th];
Clear[f]
lp = ListPlot[answer];
f1 = Fit[answer, {Sin[2*Pi*10*x], Cos[2*Pi *10*x]},x]
fp1 = Plot[f1,{x,0,.2}];
Show[lp,fp1]
f[xx_]:=f1/. x-> xx
errs = Abs[answer[[All,2]]-Table[ f[pt], {pt,answer[[All,1]]}]];
fractionalErr = Total[errs]/(Length[errs]*Max[answer]);
LogTest`Assert[fractionalErr <= 0.02];


LogTest`TestName["Outputing waveform two channel"];
Clear[data,th,ans,f0,f1,ch0,ch1,fe];
data = Transpose[Table[{Sin[x],Cos[x]}//N,{x,0,2* Pi-2*Pi/100,2*Pi/100}]];
th = OutputWaveform[{0,1},data, 10000.0,1,SampleMode -> Continuous,TransferMechanism -> Interrupts,MessageLevel ->0];
ListPlot[ans = GetVoltages[{0,3},10000.0,200,MessageLevel->0,TransferMechanism ->DMA],Joined->True,Mesh->All];
ClearTask[th];

{ch0, ch1} =ans;
f0[xx_]=Fit[ch0, {Sin[2*Pi*100*x], Cos[2*Pi *100*x]},x]/.x->xx;
f1[xx_]=Fit[ch1, {Sin[2*Pi*100*x], Cos[2*Pi *100*x]},x]/.x->xx;
p1 =ListPlot[{ch0,ch1}];
p2 = Plot[{f0[t],f1[t]},{t,0,.01}];
Show[p1,p2]
errs = Abs[ans[[All,All,2]]-Transpose[Table[ {f0[pt], f1[pt]}, {pt,ans[[1,All,1]]}]]];
fe = Total[errs,2]/Length[Flatten[errs]]
LogTest`Assert[fe <= 0.02]



LogTest`TestName["Setuponly reading two arrays of Voltages"]
val0 = 1.23; val1=2.34; NN = 1000;
thWrite0 = OutputWaveform[{0},{0.0},10,10,SetupOnly->True,MessageLevel->0];
thWrite1 = OutputWaveform[{1},{0.0},10,10,SetupOnly->True,MessageLevel->0];
RunTask[thWrite0,val0];
RunTask[thWrite1,val1];
thTemp1 = GetVoltages[{0},10000.0,NN,MessageLevel->0,SetupOnly->True];
thTemp2 = GetVoltages[{3},10000.0,NN,MessageLevel->0,SetupOnly->True];
{err1,err2 } ={Abs[Total[RunTask[thTemp1]]/1000 -val0], Abs[Total[RunTask[thTemp2]]/1000 -val1]}
ClearTask[thTemp1];ClearTask[thTemp2];ClearTask[thWrite0];ClearTask[thWrite1];
{err1 <=.02, err2<=.02}
(err1 <=.02)&& (err2<=.02)
LogTest`Assert[(err1 <=.01)&& (err2<=.01)]


LogTest`TestName["Serial Port test of Cpp function"]
listforcall={{"messageToSend","Hello World\a more"},{"listenForReply",1},{"messagelevel",0},{"timeout",0.30},{"timeoutIsErr",0}, {"charsToRead",30}, {"terminationChar","\a"}};
response = SerialPortCommunicateCpp[listforcall]
LogTest`Assert[response== "Hello World"]


LogTest`TestName["Testing GetVoltagesTrig Positive Slope"];
numPts=100; fout = 10000.0; 
Clear[p1];Clear[p2];data2={0,0};
data = Transpose[Table[{Sin[x],Cos[x]}//N,{x,0,(2* Pi)*(1-1/numPts),2*Pi/numPts}]];
t1 = AbsoluteTime[];
th = OutputWaveform[{0,1},data, fout,1,SampleMode -> Continuous,TransferMechanism -> Interrupts,MessageLevel ->0];
Print["Output takes:", AbsoluteTime[]-t1];
(* data2 = GetVoltages[{0},10000.0,2000,MessageLevel->0,TransferMechanism -> Interrupts]; *)
t1 = AbsoluteTime[];
Pause[.1]
Print["Pause takes:", AbsoluteTime[]-t1];
cond ={};
Table[
(
t1 = AbsoluteTime[];
data2 = GetVoltagesTrig[{0},50000.0,500,0,triggerLevel, TriggerSlope->Rising, MessageLevel->0,TransferMechanism ->DMA];
Print["acquistion takes:", AbsoluteTime[]-t1];
 Print[ triggerLevel," --> ", data2[[1]][[2]]] ;
p1 = ListPlot[data2];
cond = Append[cond,data2[[1]][[2]] - triggerLevel >=0];
cond = Append[cond, data2[[1]][[2]] - triggerLevel <= ( data[[1]][[2]]- data[[1]][[1]])*1.5];
),
{triggerLevel,{-.2,0.2,.5}}];
cond

p2 =ListPlot[Table[{i/fout,data[[1]][[i]]},{i,1,numPts-1}],Joined->True];
ClearTask[th];
Show[p1,p2]
LogTest`Assert[And @@ cond];


LogTest`TestName["Checking trigger level is between pre and post trigger data"];
numPts=200; fout = 10000.0; 
Clear[ans, cond];
Clear[p1];Clear[p2];data2={0,0};
data = Transpose[Table[{Sin[x],Cos[x]}//N,{x,0,(2* Pi)*(1-1/numPts),2*Pi/numPts}]];
th = OutputWaveform[{0,1},data, fout,1,SampleMode -> Continuous,TransferMechanism -> DMA,MessageLevel ->0];
preNum = 10; postNum =5;
ans = GetVoltagesTrig[{0},10000.0,postTriggerSamples = 5,0,triggerLevel=0.0,PreTriggerSamples->10,MessageLevel->0,TransferMechanism ->DMA, IncludeTime->Omit];  (* Note sample mode currently hard wired to continuous *)
{ans[[preNum]], triggerLevel,ans[[preNum+1]]};
cond = {};
cond = Append[cond,Length[ans] == preNum + postNum];
cond = Append[cond, ans[[preNum]]< triggerLevel< ans[[preNum+1]]];
ClearTask[th];
LogTest`Assert[And @@ cond];



LogTest`TestName["SoftwareTriggering multiple Channels with PreTrigger Samples"];
Clear[ans, cond];
numPts=500; fout = 1000.0; Clear[ans, cond, p1,p2];
eps =1.0 * 10^-2;
waveOut = Transpose[Join[Table[{0.0,-2.0},{10}],{{1.0,-1.0}},Table[{0.4,-1.5},{10}]]]
th = OutputWaveform[{0,1},waveOut, fout,1,SampleMode -> Continuous,TransferMechanism -> DMA,MessageLevel ->0];
ans = GetVoltagesTrig[channels ={0,3,1},10000.0,postTriggerSamples = 50,0,triggerLevel=0.5,PreTriggerSamples->(preTrigSamples = 15),MessageLevel->0,TransferMechanism ->DMA, IncludeTime->Omit];
cond ={};
cond =Append[cond,Dimensions[ans]=={Length[channels], postTriggerSamples+preTrigSamples}];
cond = Append[cond,(Abs[Part[ans,1,preTrigSamples]- 0.0 ] < eps) ||                                 (* last pretrigger samples trigger channel *)
					(Abs[Part[ans,1,preTrigSamples-1]- 0.0 ] < eps)];                   (* one previous to allow for finite rise timing *)
cond = Append[cond,(Abs[Part[ans,2,preTrigSamples] - (-2.0)] <eps) ||                            (* last pretrigger sample first NON-triggger channel *)
			(Abs[Part[ans,2,preTrigSamples-1 ] - (-2.0)] <eps)];                               (* one sample timing error OK *)
cond = Append[cond,Abs[Part[ans,1,preTrigSamples + 1]- 1.0 ] < eps];
cond = Append[cond,Abs[Part[ans,2,preTrigSamples +1 ] - (-1.0)] <eps];
cond;
ClearTask[th];
OutputWaveform[{0,1},{{0},{0}},1,1]
ListPlot[ans, PlotJoined->True]
LogTest`Assert[And@@cond];


LogTest`TestName["SoftwareTriggering multiple non sequential Channels with PreTrigger Samples"];
Clear[ans, cond];
numPts=500; fout = 1000.0; Clear[ans, cond, p1,p2];
eps =1.0 * 10^-2;
waveOut = Transpose[Join[Table[{0.0,-2.0},{10}],{{1.0,-1.0}},Table[{0.4,-1.5},{10}]]]
th = OutputWaveform[{0,1},waveOut, fout,1,SampleMode -> Continuous,TransferMechanism -> DMA,MessageLevel ->0,ActiveEdge->Falling];


ans = GetVoltagesTrig[channels ={3,0},10000.0,postTriggerSamples = 50,trigChannel = 0,triggerLevel=-1.2,PreTriggerSamples->(preTrigSamples = 15),MessageLevel->0,TransferMechanism ->Interrupts, IncludeTime->Omit];
cond ={};
cond =Append[cond,Dimensions[ans]=={Length[channels], postTriggerSamples+preTrigSamples}];  (* FIX number returned not current garenteed to be pretrig+postrigger samples returned -- check pretrigsamples available before arming trigger*)
cond = Append[cond,Abs[Part[ans,2,preTrigSamples-1]- 0.0 ] < eps];  (* channels switched in GetVoltageTrig *)
cond = Append[cond,Abs[Part[ans,1,preTrigSamples] - (-2.0)] <eps]; 
cond = Append[cond,Abs[Part[ans,2,preTrigSamples + 1]- 1.0 ] < eps];
cond = Append[cond,Abs[Part[ans,1,preTrigSamples +1 ] - (-1.0)] <eps];
cond
ClearTask[th];
OutputWaveform[{0,1},{{0},{0}},1,1];
ListPlot[ans, PlotJoined->True]
LogTest`Assert[And@@cond];



LogTest`TestName["Testing GetVoltagesTrig Negative Slope"];
numPts=100; fout = 10000.0; 
Clear[p1];Clear[p2];data2={0,0};
data = Transpose[Table[{Sin[x],Cos[x]}//N,{x,0,(2* Pi)*(1-1/numPts),2*Pi/numPts}]];
th = OutputWaveform[{0,1},data, fout,1,SampleMode -> Continuous,TransferMechanism -> DMA,MessageLevel ->0];
(* data2 = GetVoltages[{0},10000.0,2000,MessageLevel->0,TransferMechanism -> Interrupts]; *)
cond ={};
Table[
(
data2 = GetVoltagesTrig[{0},50000.0,500,0,triggerLevel,TriggerSlope->Falling, MessageLevel->0,TransferMechanism ->Interrupts];
 Print[ triggerLevel," --> ", data2[[1]][[2]]] ;
p1 = ListPlot[data2];
cond = Append[cond,data2[[1]][[2]] - triggerLevel <=0];
cond = Append[cond, data2[[1]][[2]] - triggerLevel <= ( data[[1]][[2]]- data[[1]][[1]])*1.5];
),
{triggerLevel,{-.2,0.2,.5}}];
cond
p2 =ListPlot[Table[{i/fout,data[[1]][[i]]},{i,1,numPts-1}],Joined->True];
ClearTask[th];
Show[p1,p2]
LogTest`Assert[And @@ cond];


runSampleNumberCheck[fout_Real] :=
(
numPts=500; Clear[ans, cond, p1,p2];
eps =1.0 * 10^-2;
waveOut = Join[Table[0.,{10}],Table[5.0,{10}]];
th = OutputWaveform[{0},waveOut, fout,1,SampleMode -> Continuous,TransferMechanism ->DMA,MessageLevel ->0];
ans = GetVoltagesTrig[channels ={0},10000.0,postTrigSamples = 50,0,triggerLevel=1.5,PreTriggerSamples->(preTrigSamples = 100),MessageLevel->0,TransferMechanism ->DMA, IncludeTime->Omit];
{Length[ans], preTrigSamples,postTrigSamples};
Length[ans] == preTrigSamples+postTrigSamples;
cond={Length[ans] == preTrigSamples+postTrigSamples};
And@@cond;
ClearTask[th];
OutputWaveform[{0,1},{{0},{0}},1,1];
And@@cond
)

(* Number of samples taken spans more than a period of the input signal. *)
LogTest`TestName["Sample number equals pretrigger + posttrigger for multiple cycles of input"];
sampleConditions = runSampleNumberCheck[10000.0];
ListPlot[ans, PlotJoined->True]
LogTest`Assert[And@@sampleConditions];

(* The sample interval is small compared to the input signal period *)
LogTest`TestName["Sample number equals pretrigger + posttrigger for slow input signal"];
sampleConditions = runSampleNumberCheck[100.0]
ListPlot[ans, PlotJoined->True]
ans;
LogTest`Assert[ And@@sampleConditions];

(* 
A very slow test disabled by default!!
sampleConditions = runSampleNumberCheck[0.10]
LogTest`Test["Sample number equals pretrigger + posttrigger for slow input signal", And@@sampleConditions];
ListPlot[ans, PlotJoined->True]
*)


LogTest`TestName["Digital triggering one channel"];
 Clear[ansDigital,ansAnalog, conds, plots,plotDigital,plotAnalog];
numPts=100; fout = 1000.0;
fin =1000.0;preTrigSamples = 10;postTriggerSamples = 30;
commonOpts = Sequence[SampleMode -> Finite, PreTriggerSamples->preTrigSamples,MessageLevel->0,TransferMechanism ->Interrupts,TriggerSlope->Rising,IncludeTime->Omit];

p1 = ListPlot[waveOut = Transpose[Join[Table[{-1,4.0},{numPts/2}],Table[{5.5,-1.0},{numPts/2}]]],Joined->True];
t1=AbsoluteTime[];
th = OutputWaveform[{0,1},waveOut, fout,1,SampleMode -> Continuous,TransferMechanism -> DMA,MessageLevel ->0];
Print["OutputWaveform took: ", AbsoluteTime[]-t1, " seconds"];
plots={};
conds ={};


(* first test trigger on signal that you are recording *)
t1=AbsoluteTime[];
ansDigital = GetVoltagesDigTrig[channels ={0},fin,postTriggerSamples,trigChannel = 0,commonOpts];
Print["Digital triggering took: ", AbsoluteTime[]-t1, " seconds"];
conds = Append[conds,ansDigital[[preTrigSamples]] < 2.5 < ansDigital[[preTrigSamples +1]] ];
plots= Append[plots, ListPlot[ansDigital,PlotRange -> All]];


(* Software triggering takes too long at slow speeds suspect finite number in testing array must be read before returning *)
t1=AbsoluteTime[];
ansAnalog= GetVoltagesTrig[channels ={0},fin,postTriggerSamples,trigChannel = 0,triggerLevel=2.0,commonOpts];
Print["Software triggering took: ", AbsoluteTime[]-t1, " seconds"];
 conds = Append[conds, ansAnalog[[preTrigSamples]] < triggerLevel < ansAnalog[[preTrigSamples+1]] ]; 
plots = Append[plots,ListPlot[ansAnalog,PlotRange -> All, Joined->True]];
conds;
Show[plots,PlotRange->All]

ClearTask[th];
OutputWaveform[{0,1},{{0},{0}},1,1];
LogTest`Assert[And@@conds]


LogTest`TestName["Digital triggering two channels of Data"];
 Clear[ansDigital,ansAnalog, conds, plots,plotDigital,plotAnalog];
numPts=100; fout = 10000.0;
fin =10000.0;preTrigSamples = 15;postTriggerSamples = 20;
commonOpts = Sequence[ PreTriggerSamples->preTrigSamples,MessageLevel->0,TriggerSlope->Rising,IncludeTime->Omit,TransferMechanism ->Interrupts];

p1 = ListPlot[waveOut = Transpose[Join[Table[{-1,-2},{100}],Table[{5,-2.5},{100}]]],Joined->True];
th = OutputWaveform[{0,1},waveOut, fout,1,SampleMode -> Continuous,TransferMechanism ->DMA,MessageLevel ->0];
plots={};
conds ={};

(* first test trigger on signal that you are recording *)
{ansDigital,extraDigital} = GetVoltagesDigTrig[channels ={0,3},fin,postTriggerSamples,trigChannel = 0,commonOpts,SampleMode -> Continuous];
conds = Append[conds,ansDigital[[preTrigSamples]] < 2.5 < ansDigital[[preTrigSamples +1]] ];
plots= Append[plots, ListPlot[{ansDigital,extraDigital}]];

(* Software triggering takes too long at slow speeds suspect finite number in testing array must be read before returning *)
{ansAnalog,extraAnalog}= GetVoltagesTrig[channels ={0,3},fin,postTriggerSamples,trigChannel = 0,triggerLevel=2.0,commonOpts,SampleMode -> Continuous];
 conds = Append[conds, ansAnalog[[preTrigSamples]] < triggerLevel < ansAnalog[[preTrigSamples+1]] ]; 
plots = Append[plots,ListPlot[{ansAnalog, extraAnalog}, Joined->True]];
conds;

Show[plots,PlotRange-> All]

ClearTask[th];
OutputWaveform[{0,1},{{0},{0}},1,1];
LogTest`Assert[And@@conds]



LogTest`TallyTests[]



